// eslint-disable-next-line @typescript-eslint/no-unused-vars
import { jsPlumbInstance, jsPlumb, OnConnectionBindInfo } from 'jsplumb'
import { ref } from 'vue'
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import { jsplumbSetting } from '../config/default'

export function useJsplumb() {
  // 实例化的jsplumb对象
  const jsPlumbInstance = ref({} as jsPlumbInstance)
  /**
   * 选中的链接线
   */
  const selectedLine = ref([] as Array<any>)
  /**
   * 初始化连线控件
   */
  const initJsPlumb = function () {
    jsPlumbInstance.value.ready(() => {
      // 完成连线前的校验 可绑定事件避免源和目标在同一出上
      jsPlumbInstance.value.bind('beforeDrop', function (conn) {
        console.log('jsPlumb-beforeDrop')
        if (conn.sourceId === conn.targetId) {
          return false
        } else {
          return true
        }
      })

      /**
       * 点击事件
       */
      jsPlumbInstance.value.bind('click', function (conn: any) {
        console.log('jsPlumb-click')
        selectedLine.value = conn
      })
      /**
       * 连线事件将源和目标设置为不可用
       */
      jsPlumbInstance.value.bind('connection', function (info, e) {
        console.log('jsPlumb-connection', e)
        jsPlumbInstance.value.setTargetEnabled(info.target, false)
      })
      /**
       * 删除事件将源和目标设置为可用
       */
      jsPlumbInstance.value.bind('connectionDetached', function (info, e) {
        console.log('jsPlumb-connectionDetached', e)
        jsPlumbInstance.value.setTargetEnabled(info.target, true)
      })

      /**
       * 移动事件
       */
      jsPlumbInstance.value.bind(
        'connectionMoved',
        function (info: OnConnectionBindInfo, e) {
          console.log('jsPlumb-connectionMoved', e)
          if (info.newTargetId !== info.originalTargetId) {
            // 拖动目标列
            jsPlumbInstance.value.setTargetEnabled(info.originalTargetId, true)
          }
        },
      )

      /**
       * 拖动事件
       */
      jsPlumbInstance.value.bind('connectionDrag', function (info, e) {
        console.log('jsPlumb-connectionDrag', info, e)
      })
    })
  }

  return {
    initJsPlumb,
    jsPlumbInstance,
  }
}
